package com.sv.web;

import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolContext;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.config.XmlFactoryConfiguration;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.servlet.view.velocity.VelocityView;

public class VelocityToolboxView extends
        org.springframework.web.servlet.view.velocity.VelocityToolboxView {

    private Resource toolboxConfigResource;

    public Resource getToolboxConfigResource() {
        return toolboxConfigResource;
    }

    public void setToolboxConfigResource(Resource toolboxConfigResource) {
        this.toolboxConfigResource = toolboxConfigResource;
    }

    @Override
    protected Context createVelocityContext(Map model,
            HttpServletRequest request, HttpServletResponse response)
            throws IllegalStateException, IOException {
        ViewToolContext context = new ViewToolContext(getVelocityEngine(),
                request, response, getServletContext());

        context.putAll(model);

        if (null != getToolboxConfigLocation()
                || null != getToolboxConfigResource()) {
            XmlFactoryConfiguration cfg = new XmlFactoryConfiguration();

            URL url;
            if (null != getToolboxConfigLocation()) {
                url = new ServletContextResource(getServletContext(),
                        getToolboxConfigLocation()).getURL();
                cfg.read(url);
            }
            else if (null != getToolboxConfigResource()) {
                url = getToolboxConfigResource().getURL();
                cfg.read(url);
            }

            ToolboxFactory factory = cfg.createFactory();

            context.addToolbox(factory.createToolbox(Scope.APPLICATION));

            context.addToolbox(factory.createToolbox(Scope.REQUEST));

            context.addToolbox(factory.createToolbox(Scope.SESSION));
        }
        return context;
    }

}
